<template>
  <main-container>
    <div class="role-create-page">
      <el-breadcrumb separator="/" class="mb30">
        <el-breadcrumb-item :to="{ name: 'roleList' }">角色设置</el-breadcrumb-item>
        <el-breadcrumb-item>{{ roleId ? '修改角色' : '添加角色' }}</el-breadcrumb-item>
      </el-breadcrumb>
      <div class="form-wrapper">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="140px">
          <el-form-item label="角色名：" prop="roleName">
            <el-input v-model="ruleForm.roleName" :maxlength="10" clearable placeholder="请输入角色名"></el-input>
          </el-form-item>
          <el-form-item label="角色描述(选填)：">
            <el-input type="textarea" v-model="ruleForm.describes" :maxlength="50" show-word-limit></el-input>
          </el-form-item>
          <el-form-item label="角色菜单：" prop="funId" required>
            <el-tree
              :data="treeData"
              :default-checked-keys="defaultCheckedKeys"
              show-checkbox
              @check-change="handleCheckChange"
              node-key="id"
              ref="tree"
              highlight-current
              :props="defaultProps"
            ></el-tree>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" class="w100" :loading="loading" @click="handleSubmit">确定</el-button>
            <router-link :to="{ name: 'roleList' }" class="ml20">
              <el-button class="w100">取消</el-button>
            </router-link>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </main-container>
</template>

<script>
import { getRole, getRoleMenuList, saveRole } from '@/api/workbench'

export default {
  name: 'roleCreate',
  data() {
    return {
      loading: false,
      defaultCheckedKeys: [],
      ruleForm: {
        roleName: '',
        describes: '',
        funId: ''
      },
      rules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          { min: 1, max: 10, message: '角色名最多填写10个字', trigger: 'blur' }
        ],
        funId: [{ required: true, message: '请勾选该角色权限', trigger: 'change' }]
      },
      treeData: []
    }
  },
  computed: {
    defaultProps() {
      return {
        children: 'children',
        label: 'title'
      }
    },
    roleId() {
      return this.$route.query.id || ''
    }
  },
  async created() {
    await this.getRoleMenuList()
    this.roleId && this.init()
  },
  methods: {
    /**
     * 根据角色id获取角色
     */
    async init() {
      let { roleId } = this
      let res = await getRole({ roleId })
      let { code, data } = res
      if (code === 0) {
        this.ruleForm = { ...data }
        this.defaultCheckedKeys = this.handleFilterHalfCheck(
          this.treeData,
          data.funId.split(',').map(item => item * 1)
        )
      }
    },
    /**
     * 查询所有操作菜单(角色编辑使用)
     */
    async getRoleMenuList() {
      let res = await getRoleMenuList()
      let { code, data } = res
      if (code === 0) {
        this.treeData = data.functionList
      }
    },
    /**
     * 节点选中状态发生变化时的回调
     */
    handleCheckChange() {
      let keys = this.$refs.tree.getCheckedKeys()
      let halfKeys = this.$refs.tree.getHalfCheckedKeys()
      this.ruleForm.funId = [...keys, ...halfKeys].join(',')
    },
    /**
     * 回写选中的节点，过滤半选中
     */
    handleFilterHalfCheck(treeData, keys) {
      return treeData.reduce((res, item) => {
        let values = []
        if (item.children && Array.isArray(item.children) && item.children.length > 0) {
          values = this.handleFilterHalfCheck(item.children, keys)
        } else if (keys.includes(item.id)) {
          values = [item.id]
        }
        return [...res, ...values]
      }, [])
    },
    /**
     * 提交
     */
    handleSubmit() {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          this.loading = true
          let res = await saveRole(this.ruleForm).catch(() => (this.loading = false))
          this.loading = false
          let { code, msg: message } = res
          if (code === 0) {
            this.$message.success(message)
            this.$router.go(-1)
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
